$(function () {
    //==========================================测试专用token============================================
    // var user = {
    //  "amount": 21732,
    //  "favorited": 0,
    //  "headImgUrl": "http://wx.qlogo.cn/mmopen/Qk0Fr32PsCWyeYR964gTpuYWCicO9u9uSt3lLmbPGCSCm243VIX7iccD8mD9sB0jZ3ROcAewa61gmylEj9sVQo7hYpHSQhV0YT/0",
    //  "nickName": "Dada",
    //  "noviceBoot": 0,
    //  "openId": "o5VWP1Gq6ul5k2m_l2W8UFe0Wzy0",
    //  "registerTime": "2017-08-22 10:19:50",
    //  "rookieAward": 1,
    //  "sex": 1,
    //  "token": "e9f786ac5f8342569fd0354e3671388f",
    //  "type": 0,
    //  "userId": 10000
    //  };
    //  // localStorage.user = JSON.stringify(user);
    // localStorage.setItem('user',JSON.stringify(user))
    //==========================================华丽丽分界线============================================
    if (!localStorage.user) {
        getCode();
    } else {
        //存在用户信息
        var user = JSON.parse(localStorage.user);
        if (user) {
            $.ajax({
                method: "POST",
                url: "/topfun/user/refersh",
                data: {
                    userId: user.userId,
                    token: user.token
                },
                success: function (result) {
                    var data = JSON.parse(result);
                    if(data.code == 0){
                        localStorage.user = data.data;
                        var user = JSON.parse(localStorage.user);
                        guanzhu(user);
                        $('#amount').html(user.amount);
                    }else{
                        getCode();
                    }
                }
            });
        }
    }

    $('.dou').click(function () {
        $('.crash .dialog-cover,.crash .comfirm,.crash .alertC').fadeIn()
    })

    $('.crash .closeBtn').on('click', function (e) {
        $(this).parents('.comfirm').fadeOut()
    })

    $('.info').click(function () {
        $('#infoAlert .dialog-cover,#infoAlert .alertC').fadeIn()
    })

    $('.closeBtn').click(function () {
        var $parent = $(this).parents('.alertC')
        $parent.fadeOut()
        $parent.siblings('.dialog-cover').fadeOut()
        var $dom = $(this).parents('.comfirm')
        console.log($dom)
        if ($dom) $dom.fadeOut()
    })

    //========================div-type "recharge" recharge-amount="20" ====================================
    $('div[div-type=recharge]').click(function () {
        var amount = $(this).attr('recharge-amount');
        var user = JSON.parse(localStorage.user) || {};
        $('#loadingToast').fadeIn();
        $.ajax({
            method: "POST",
            url: "/topfun/payment/create",
            data: {userId: user.userId, token: user.token, openId: user.openId, amount: amount, payType: 1, subject: '充值' + amount + '乐豆', description: '充值' + amount + '乐豆'},
            success: function (result) {
                console.log(result)
                if (result) {
                    var json = JSON.parse(result);
                    var data = JSON.parse(json.data);
                    var payInfo = JSON.parse(data.payInfo);
                    if (json.code == 0) { //下单成功
                        function onBridgeReady() {
                            $('#loadingToast').fadeOut();
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', payInfo,
                                function (res) {

                                    if (res.err_msg == "get_brand_wcpay_request:ok") {

                                        $.ajax({
                                            method: "POST",
                                            url: "/topfun/user/refersh",
                                            data: {
                                                userId: user.userId,
                                                token: user.token
                                            },
                                            success: function (result) {
                                                var data = JSON.parse(result);
                                                if(data.code == 0){
                                                    localStorage.user = data.data;
                                                    $('#amount').html(JSON.parse(data.data).amount);
                                                }else{
                                                    getCode();
                                                }
                                            }
                                        });
                                    }
                                }
                            );
                        }

                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
                                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                            } else if (document.attachEvent) {
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                            }
                        } else {
                            onBridgeReady();
                        }
                    } else {
                        alert(json.msg);
                    }
                }
            }
        }).fail(function () {
            alert("$.ajax /topfun/payment/create failed!");
        })
    })

})

//获取微信授权code
var getCode = function () {
    var LocString = String(window.document.location.href);
    function getQueryStr(str) {
        var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
        if (tmp = rs) {
            return tmp[2];
        }
        return "";
    }
    var code = getQueryStr("code");
    if (code == '') {//如果code=''请求授权
        location.href = '/topfun/oauth2/authorize?redirect=http:%2F%2Fwww.tuiclubs.com%2Findex.html';
    } else {
        userLogin(code);//用户登录
    }
}

/**
 * 用户登录
 */
var userLogin = function (code) {
    if (!localStorage.user) {
        $.ajax({
            method: "POST",
            url: "/topfun/user/login",
            data: {code: code},
            success: function (result) {
                if (result) {
                    console.log(result)
                    var json = JSON.parse(result);
                    localStorage.user = json.data || [];
                    var user = JSON.parse(localStorage.user);
                    guanzhu(user);
                    $('#amount').html(user.amount);
                }
            }
        }).fail(function () {
            alert("$.ajax /topfun/user/login failed!");
        })
    } else {
        var user = JSON.parse(localStorage.user);
        if (user) {
            guanzhu(user);
        }
        $('#amount').html(user.amount);
    }
}

/**
 * 关注逻辑
 */
var guanzhu = function (user) {
    if(user.noviceBoot){
        if (user.favorited) {//是否关注公众号1是0否
            if (!user.rookieAward) {//是否领取新人奖励
                $('#gzjiangalert .dialog-cover,#gzjiangalert .alertC').fadeIn();
                $.ajax({
                    method: "POST",
                    url: "/topfun/user/rookieAward",
                    data: {
                        userId: user.userId,
                        token: user.token
                    },
                    success: function (result) {
                        var data = JSON.parse(result);
                        if(data.code == 0){
                            localStorage.user = data.data;
                            user = JSON.parse(localStorage.user);
                            $('#amount').html(user.amount);
                        }
                    }
                });
            }
        } else {
            $('#gzalert .dialog-cover,#gzalert .alertC').fadeIn()
        }
    }else{
        $('.guide').fadeIn(function(){
            $('.guide .step1').fadeIn().click(function(){
                $('.guide .step1').fadeOut()
                $('.guide .step2').fadeIn().click(function(){
                    $('.guide .step2').fadeOut()
                    $('.guide .step3').fadeIn().click(function(){
                        $('.guide .step3').fadeOut()
                        $('.guide .step4').fadeIn().click(function(){
                            $.ajax({
                                method: "POST",
                                url: "/topfun/noviceBoot/finish",
                                data: {
                                    userId: user.userId,
                                    token: user.token
                                },
                                success: function (result) {
                                    var json = JSON.parse(result);
                                    if (json.code === 0) {
                                        $('.guide .step4').fadeOut(function(){
                                            $('.guide').fadeOut()
                                        })
                                    }else{//code 不等于0
                                        console.log(json.msg)
                                        $('.guide .step4').fadeOut(function(){
                                            $('.guide').fadeOut()
                                        })
                                    }
                                }
                            })

                        })
                    })
                })
            })
        })
    }
}
//==================================================分享====================================
var shareConfig = function () {
    $.ajax({
        method: "POST",
        url: "/topfun/wechat/share/config",
        data: {url:location.href.split('#')[0]},
        success: function (result) {
            var json = JSON.parse(result);
            if (json.code === 0) {
                console.log(json)
                var shareData = {
                    title: "幸运乐翻天",
                    desc: "发现一个可以赚钱的游戏，关注就送三元现金！大家快来跟我一起玩吧！",
                    link: location.href.split('#')[0],
                    imgUrl:"http://www.tuiclubs.com/static/img/code.jpg",
                    success: function () {
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                    }
                };
                var jsApiData = JSON.parse(json.data) || {};
                wx.config({
                    debug: false,
                    appId: jsApiData.appId,
                    timestamp: jsApiData.timestamp,
                    nonceStr: jsApiData.nonceStr,
                    signature: jsApiData.signature,
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                    ]
                });
                wx.ready(function(){
                    wx.onMenuShareTimeline(shareData);
                    wx.onMenuShareAppMessage(shareData);
                });
                wx.error(function(res){
                    alert(JSON.stringify(res));
                });
            }else{//code 不等于0
                console.log(json.msg)
            }
        }
    })
}
shareConfig();//分享配置